package online.yangcloud.web.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import online.yangcloud.common.annotation.SessionValid;
import online.yangcloud.common.common.ResultData;
import online.yangcloud.core.model.entity.UserEntity;
import online.yangcloud.core.model.request.SecretParameter;
import online.yangcloud.core.model.request.file.FileMerger;
import online.yangcloud.core.model.request.file.FileSizeChecker;
import online.yangcloud.core.model.request.file.FileUploadInstance;
import online.yangcloud.core.model.request.file.HashChecker;
import online.yangcloud.web.service.impl.GlobalServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuboyang
 * @since 2023年11月28 10:38:44
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Resource
    private GlobalServiceImpl globalService;

    /**
     * 检测文件大小是否允许上传，用户空间剩余量是否足够
     *
     * @param checker 文件大小
     * @return 结果
     */
    @SessionValid
    @PostMapping("/check_limit")
    public ResultData checkFileSize(@Valid @RequestBody FileSizeChecker checker, UserEntity user) {
        List<String> sizes = StrUtil.split(checker.getSizes(), StrUtil.COMMA);
        List<Boolean> flags = new ArrayList<>();
        long total = user.getUsedSpaceSize();
        for (String o : sizes) {
            long size = Long.parseLong(o);
            if (total + size <= user.getTotalSpaceSize()) {
                total += size;
                flags.add(Boolean.TRUE);
            } else {
                flags.add(Boolean.FALSE);
            }
        }
        return ResultData.success(flags);
    }

    /**
     * 检测文件块是否已在库中
     *
     * @param checker 待检测文件块列表
     * @return 检测结果：true-已存在；false-尚不存在
     */
    @SessionValid
    @PostMapping("/check_exist")
    public ResultData checkBlockExist(@Valid @RequestBody HashChecker checker) {
        return ResultData.success(globalService.acquireUpload().checkBlockExist(checker));
    }

    /**
     * 上传文件块
     *
     * @param uploader 文件块参数
     * @return 是否上传成功
     */
    @SessionValid
    @PostMapping("/upload")
    public ResultData uploadBlock(FileUploadInstance uploader) {
        return ResultData.success(globalService.acquireUpload().blockUpload(uploader));
    }

    /**
     * 合并文件
     *
     * @param parameter 请求参数
     * @param user      当前登录的用户
     * @return 上传后的文件元数据
     * @throws IOException IOException
     */
    @SessionValid
    @PostMapping("/merge")
    public ResultData merge(@Valid @RequestBody SecretParameter parameter, UserEntity user) throws IOException {
        String aes = SecureUtil.aes("12121212121212121212121212121212".getBytes()).decryptStr(parameter.getSecret());
        FileMerger merger = JSONUtil.toBean(aes, FileMerger.class);
        merger.setExt(merger.getExt().toLowerCase());
        return ResultData.success(globalService.acquireUpload().fileMerge(merger, user));
    }

}
